package com.eqxiu.iom.msg.service;

import com.alibaba.fastjson.JSONObject;
import com.eqxiu.common.codec.CodecFactory;
import com.eqxiu.iom.Model.RoutingMsgModel;
import com.eqxiu.iom.msg.dto.msg.ActionMsgTriggerDTO;
import com.eqxiu.iom.msg.dto.msg.UserInfoDTO;
import com.eqxiu.iom.msg.manager.DubboManager;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @classname: UserActionMsgService.java
 * @author: th
 * @version: 1.0
 * @description: 用户行为消息触发专用服务
 * @createtime: 2019-12-04 16:38
 */
@Service
public class UserActionMsgService {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserActionMsgService.class);

    @Autowired
    private DubboManager dubboManager;

    @Value("${queue.exchange.name.msgcenter}")
    private String msgCenterExchange;

    @Value("${queue.routing.key.msgcenter}")
    private String msgCenterRoutingKey;

    /**
     * @description 发送消息到用户行为触发消息MQ
     * @param dto
     */
    public void sendUserActionMsg(ActionMsgTriggerDTO dto) {

        LOGGER.info("UserActionMsgService.sendUserActionMsg,入参 dto:{},ext:{}", dto, dto.getExt());

        // todo RoutingMsgModel为内部流传dto 组装逻辑待优化
        List<RoutingMsgModel> routingMsgModels = new ArrayList<>();
        for (UserInfoDTO userInfoDTO : dto.getUserInfoDTOs()) {
            RoutingMsgModel routingMsgModel = new RoutingMsgModel();
            routingMsgModel.setUserid(userInfoDTO.getUserid());
            routingMsgModel.setLoginName(userInfoDTO.getLoginName());
            routingMsgModel.setUserType(userInfoDTO.getUserType() + "");
            routingMsgModel.setEventCode(dto.getEventCode());
            routingMsgModel.setProducerCode(dto.getProducerCode());
            // 发送时间业务暂时不支持
//            routingMsgModel.setSendTime(new Date(dto.getSendTimestamp()));
            Map<String, Object> params = new HashMap<>();
            Map<String, Object> paramMap = new HashMap<>();
            if (StringUtils.isNotBlank(routingMsgModel.getLoginName())) {
                paramMap.put("loginName", routingMsgModel.getLoginName());
            }
            if (!CollectionUtils.isEmpty(dto.getParams())) {
                paramMap.putAll(dto.getParams());
            }
            params.put("params", paramMap);
            routingMsgModel.setBody(params);

            if (!CollectionUtils.isEmpty(dto.getExt())) {
                routingMsgModel.setExt(dto.getExt());
            }

            routingMsgModels.add(routingMsgModel);
        }

        try {
            LOGGER.info("SendMessage  >>> 发送消息到RabbitMQ, 交换器:  " + msgCenterExchange + " 路由键: " + msgCenterRoutingKey + "  消息内容: {}", JSONObject.toJSONString(routingMsgModels));
            // springboot 2.x 更换 eqxiu-boot-xxx modified by wangl 2020-05-28
//            msgCenterMessageProvider.sendMessage(CodecFactory.getCodec().serialize(routingMsgModels), msgCenter);
            dubboManager.getMaxcenterRabbitTemplate().convertAndSend(msgCenterExchange, msgCenterRoutingKey, CodecFactory.getCodec().serialize(routingMsgModels));
        } catch (Exception e) {
            LOGGER.error("Send message 推送异常: " + JSONObject.toJSONString(dto) + ", exception: ", e);
        }
    }
}
